<template>
  <div class="app-container">
    <!-- 查询表单部分 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="数据版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入数据版本号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后更新人" prop="updateBy">
        <el-input
          v-model="queryParams.updateBy"
          placeholder="请输入最后更新人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮部分 -->
    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:agreement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:agreement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:agreement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:agreement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示部分 -->
    <div class="el-table-wrapper" ref="tableWrapper">
      <el-table v-loading="loading" :data="agreementList" @selection-change="handleSelectionChange" style="width: 100%;">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户唯一标识" align="center" prop="id" :width="columnWidths.id" />
        <el-table-column label="用户类型" align="center" prop="type" :width="columnWidths.type" />
        <el-table-column label="用户描述信息" align="center" prop="content" :width="columnWidths.content">
          <template #default="scope">
            <div
              class="content-preview"
              @click="toggleContent(scope.$index)"
              :data-expanded="expandedIndices.includes(scope.$index)"
            >
              <div v-if="expandedIndices.includes(scope.$index)" class="pre-wrap-content">{{ removePTags(scope.row.content) }}</div>
              <div v-else class="pre-wrap-content">{{ removePTags(scope.row.content).slice(0, 12) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数据版本号" align="center" prop="version" :width="columnWidths.version" />
        <el-table-column label="创建时间" align="center" prop="updateTime" :width="columnWidths.updateTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后更新人" align="center" prop="updateBy" :width="columnWidths.updateBy" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="columnWidths.operation">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:agreement:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:agreement:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改协议信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="agreementRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入用户类型" />
        </el-form-item>
        <el-form-item label="用户描述信息" prop="content">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="数据版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入数据版本号" />
        </el-form-item>
        <el-form-item label="最后更新人" prop="updateBy">
          <el-input v-model="form.updateBy" placeholder="请输入最后更新人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页部分 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-bottom"
    />
  </div>
</template>

<script setup name="Agreement">
  import { listAgreement, getAgreement, delAgreement, addAgreement, updateAgreement } from "@/api/checksystem/agreement";
  import { ElMessage } from 'element-plus';
  import { getCurrentInstance, ref, reactive, toRefs, onMounted, onUnmounted } from 'vue';
  import { parseTime } from '@/utils/ruoyi';

  const { proxy } = getCurrentInstance();
  const tableWrapper = ref(null);
  const columnWidths = ref({
    id: 0,
    type: 0,
    content: 0,
    version: 0,
    updateTime: 0,
    updateBy: 0,
    operation: 0
  });

  // 数据状态定义
  const agreementList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const expandedIndices = ref([]);

  // 移除 p 标签
  const removePTags = (content) => {
    return content? content.replace(/<p>/g, '').replace(/<\/p>/g, '') : '';
  };

  const toggleContent = (index) => {
    if (expandedIndices.value.includes(index)) {
      expandedIndices.value = expandedIndices.value.filter((i) => i!== index);
    } else {
      expandedIndices.value.push(index);
    }
  };

  const data = reactive({
    form: {
      id: null,
      title: '',
      content: '',
      type: '用户协议', // 默认用户协议
      status: 1, // 默认启用
      createTime: null,
      updateTime: new Date(),
      updateBy: '',
      isDeleted: 0
    },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      type: null,
      content: null,
      version: null,
      updateTime: null,
      updateBy: null,
      params: {}
    },
    rules: {
      title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择协议类型', trigger: 'change' }
      ],
      version: [
        { required: true, message: '请输入数据版本号', trigger: 'blur' }
      ]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  // 查询协议信息列表
  function getList() {
    loading.value = true;
    queryParams.value.params = queryParams.value.params || {};
    listAgreement(queryParams.value).then(response => {
      agreementList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }).catch(error => {
      loading.value = false;
      proxy.$message.error(`加载数据失败: ${error.message || '未知错误'}`);
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      title: '',
      content: '',
      type: '用户协议', // 默认用户协议
      status: 1, // 默认启用
      createTime: null,
      updateTime: new Date(),
      updateBy: '',
      isDeleted: 0
    };
    proxy.resetForm("agreementRef");
  }

  // 搜索按钮操作
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  // 重置按钮操作
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value =!selection.length;
  }

  // 新增按钮操作
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加协议信息";
  }

  // 修改按钮操作
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getAgreement(_id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改协议信息";
    });
  }

  // 提交按钮
  function submitForm() {
    proxy.$refs["agreementRef"].validate(valid => {
      if (valid) {
        const loading = proxy.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        try {
          // 设置更新时间为当前时间并格式化为字符串
          form.value.updateTime = parseTime(new Date());
          
          if (form.value.id != null) {
            updateAgreement(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            }).catch(error => {
              proxy.$modal.msgError(`修改失败: ${error.message || '未知错误'}`);
            }).finally(() => {
              loading.close();
            });
          } else {
            addAgreement(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            }).catch(error => {
              proxy.$modal.msgError(`新增失败: ${error.message || '未知错误'}`);
            }).finally(() => {
              loading.close();
            });
          }
        } catch (e) {
          loading.close();
          proxy.$modal.msgError(`提交失败: ${e.message}`);
        }
      }
    });
  }

  // 删除按钮操作
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除协议信息编号为"' + _ids + '"的数据项？').then(function () {
      return delAgreement(_ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  // 导出按钮操作
  function handleExport() {
    proxy.download('checksystem/agreement/export', {
     ...queryParams.value
    }, `agreement_${new Date().getTime()}.xlsx`);
  }

  const resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const tableWidth = entry.contentRect.width;
      const fixedWidth = 55; // 选择列的宽度
      const remainingWidth = tableWidth - fixedWidth;

      // 这里可以根据各列的重要性和大致比例分配宽度
      const columnRatios = {
        id: 0.1,
        type: 0.1,
        content: 0.3,
        version: 0.15,
        updateTime: 0.15,
        updateBy: 0.1,
        operation: 0.1
      };

      Object.keys(columnRatios).forEach(key => {
        columnWidths.value[key] = remainingWidth * columnRatios[key];
      });
    }
  });

  onMounted(() => {
    if (tableWrapper.value) {
      resizeObserver.observe(tableWrapper.value);
      const tableWidth = tableWrapper.value.offsetWidth;
      const fixedWidth = 55; // 选择列的宽度
      const remainingWidth = tableWidth - fixedWidth;

      const columnRatios = {
        id: 0.1,
        type: 0.1,
        content: 0.3,
        version: 0.15,
        updateTime: 0.15,
        updateBy: 0.1,
        operation: 0.1
      };

      Object.keys(columnRatios).forEach(key => {
        columnWidths.value[key] = remainingWidth * columnRatios[key];
      });
    }
  });

  onUnmounted(() => {
    if (tableWrapper.value) {
      resizeObserver.unobserve(tableWrapper.value);
    }
  });

  getList();
</script>

<style>
 .mb8 {
    margin-bottom: 8px;
  }

 .content-preview {
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 8px;
    white-space: pre-wrap;
    cursor: pointer;
    transition: all 0.3s ease;
    overflow-wrap: break-word; /* 保证文字在框内换行 */
    max-width: 100%; /* 防止内容溢出 */
  }

 .content-preview[data-expanded="true"] {
    background-color: #f9f9f9;
  }

 .pre-wrap-content {
    white-space: pre-wrap;
    overflow-wrap: break-word; /* 保证文字在框内换行 */
    max-width: 100%; /* 防止内容溢出 */
  }

 .el-table-wrapper {
    width: 100%;
    overflow: hidden; /* 隐藏滚动条 */
  }

 .pagination-bottom {
    margin-top: 20px;
    margin-left: 20px; /* 新增：添加左边距 */
    display: flex;
    justify-content: flex-start; /* 新增：左对齐 */
  }
</style>